from zope.interface import implements

from twisted.plugin import IPlugin
from twisted.internet import defer

from pyhnode import interfaces, config

import re, os, time

class uptimePlugin:

    implements(IPlugin, interfaces.IPlugins)

    def getConfig(self, name):
        return  ";title:uptime|uptime#stype:GAUGE;label:uptime"

    def getNames(self):
        return ["uptime"]

    def configure(self):
        platf = config.conf.get('general', 'platform')
        if platf == "linux":
            self.getValue = self.getLinuxValueDeferred
            self.getAlert = self.getLinuxAlert
        elif platf == "solaris":
            self.getValue = self.getSolarisValueDeferred
            self.getAlert = self.getSolarisAlert

    def getAlert(self, name):
        return False

    def getValue(self, name):
        pass

    def getLinuxValue(self, name):
        global alert
        try :
                f = open("/proc/uptime")
                cont = f.read().split()
                f.close()
        except :
                return [str(int(time.time())), "0"]
        val = int(float(cont[0])/3600)
        return [str(int(time.time())), {'uptime' : val}]

    def getLinuxValueDeferred(self, name):
        return defer.succeed(self.getLinuxValue(name))

    def getSolarisValue(self, name):
        output = os.popen("uptime").read()
        m = re.search("up (\d+) day\(s\),\s+(\d+):", output)
        if not m:
            m = re.search("up (\d+) hour", output)
            if not m:
                return [str(int(time.time())), "0"]
            return [str(int(time.time())), str(m.groups()[0])]
        d,h = map(int, m.groups())
        return [str(int(time.time())), {"uptime" : str(d*24+h)}]

    def getSolarisValueDeferred(self, name):
        return defer.succeed(self.getSolarisValue(name))
    
    def getLinuxAlert(self, name):
        return False

    def getSolarisAlert(self, name):
        return False

up = uptimePlugin()

